package com.cn.conf;

import static springfox.documentation.builders.PathSelectors.regex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StopWatch;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * API doc -- SPRINGFOX swagger configuration
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig implements EnvironmentAware {
    private final Logger log = LoggerFactory.getLogger(SwaggerConfig.class);
    public static final String DEFAULT_INCLUDE_PATTERN = "/api/.*";
    private RelaxedPropertyResolver propertyResolver;

    @Override
    public void setEnvironment(Environment environment) {
        this.propertyResolver = new RelaxedPropertyResolver(environment, "swagger.");
    }

    @Bean
    public Docket swaggerSpringfoxDocket() {
        log.info("Starting Swagger");
        StopWatch watch = new StopWatch();
        watch.start();
        Docket swaggerSpringMvcPlugin = new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .genericModelSubstitutes(ResponseEntity.class)
                .select()
                .paths(regex(DEFAULT_INCLUDE_PATTERN)) // and by paths
                .build();
        watch.stop();
        log.info("Started Swagger in {} ms", watch.getTotalTimeMillis());
        return swaggerSpringMvcPlugin;
    }
    
    
    /**
     * 获取API版权信息
     * 
     * title：10085电商营销API接口
     * description：REST风格API
     * 
     * @return
     */
    private ApiInfo apiInfo() {
        return new ApiInfo(
                propertyResolver.getProperty("title"),//大标题
                propertyResolver.getProperty("description"),//小标题
                propertyResolver.getProperty("version"),//版本
                propertyResolver.getProperty("termsOfServiceUrl"),
                new Contact(propertyResolver.getProperty("contact"), "", "") ,//作者信息
                propertyResolver.getProperty("license"),//链接显示文字
                propertyResolver.getProperty("licenseUrl")//网站链接
        );
    }
}